import { _decorator, assetManager, AssetManager, BoxCollider2D, Button, Color, Component, Contact2DType, Director, director, ERigidBody2DType, find, instantiate, Label, Layers, math, Node, physics, Prefab, resources, RigidBody2D, Skeleton, sp, Sprite, SpriteFrame, Tween, tween, UIOpacity, UITransform, v2, v3, Vec2 } from 'cc';
import { Biont } from './Biont';
import { getDistance, randomNum } from '../script/utils/utils';
import { Dictionary } from '../script/utils/Dictionary';
import { TouchMoveShi } from './TouchMoveShi';
import { UserInfo } from '../script/UserInfo';
import { AudioMgr } from '../script/utils/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('GameMgrShi')
export class GameMgrShi extends Component {

    static ins: GameMgrShi = null;
    mapBoundary = v2(5170, 5000)
    @property(Node)
    otherBiontRoot: Node;
    @property(Prefab)
    biontPre: Prefab;
    @property(Node)
    player: Node;
    @property(Node)
    addtionBiontRoot: Node;
    @property(Node)
    setPanel: Node;
    @property(Node)
    winPanel: Node;
    @property(Node)
    failPanel: Node;
    @property(Node)
    revivePanel: Node;
    @property(Prefab)
    widowTipPre:Prefab;
    @property(Label)
    shenkunTimeLabel:Label
    @property(Node)
    shenkunBtn: Node;

    isGameIng = true;
    currControlBiontType = 43;
    biontId = 0;

    private isImmortal = false;
    get IsImmortal() {
        return this.isImmortal;
    }
    set IsImmortal(value) {
        if (this.isImmortal == value) {
            return;
        }
        this.isImmortal = value;

        if (value == true) {
            //隐身效果
            tween(this.player.children[0].getChildByName("sp").getComponent(UIOpacity))
                .to(0.4, { opacity: 100 })
                .to(0.4, { opacity: 255 })
                .to(0.4, { opacity: 100 })
                .union()
                .repeatForever()
                .start()

        }
        else {
            Tween.stopAllByTarget(this.player.children[0].getChildByName("sp").getComponent(UIOpacity));
            this.player.children[0].getChildByName("sp").getComponent(UIOpacity).opacity=255;
        }
    }
    

    hasBiontsDic: Dictionary<number, number> = new Dictionary();//玩家拥有的生物字典，包含自己

    protected onLoad(): void {
        GameMgrShi.ins = this;
    }

    start() {
        this.player.children[0].getChildByName("sp").getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.beginTouch)
        this.createOtherBiont(43, 100);
        this.createOtherBiont(44, 35);
        this.createOtherBiont(45, 25);
        this.createOtherBiont(46, 10);
        this.createOtherBiont(47, 5);
        this.hasBiontsDic.set(999, 43);
        this.IsImmortal=true;

        //5秒后自动解除
        this.scheduleOnce(()=>{
            this.IsImmortal=false;
        },5)
        if (UserInfo.isAudioBgm) {
            AudioMgr.ins.play("audio/bgm");
        }
        else{
            AudioMgr.ins.stop();
        }
    }

    beginTouch(self, other) {
        director.once(Director.EVENT_AFTER_PHYSICS, () => {
            if (other.node.parent.getComponent(Biont)) {
                let otherType = other.node.parent.getComponent(Biont).biontType;
                if (otherType > GameMgrShi.ins.currControlBiontType) {
                    if (GameMgrShi.ins.IsImmortal == true) {
                        console.log("无敌不死")
                    }
                    else {
                    GameMgrShi.ins.gameOver();
                    console.log("游戏结束")
                    }
                }
                else {
                    GameMgrShi.ins.captureBiont(otherType);
                    other.node.destroy();
                    let type=randomNum(GameMgrShi.ins.currControlBiontType-1,GameMgrShi.ins.currControlBiontType+1);
                    if (type<43) {
                        type=43
                    }
                    if (type>67) {
                        type=67
                    }
                    GameMgrShi.ins.createOtherBiontNotNearlySelf(type,1);
                }
            }

        })
    }

    update(deltaTime: number) {
    }

    createOtherBiont(type, num) {
        resources.loadDir(`shi/spine/shanhai_${type}`, sp.SkeletonData, (err, data) => {
            if (err) {
                console.log(err);
                return;
            } else {
                for (let i = 0; i < num; i++) {
                    let pre = instantiate(this.biontPre);
                    let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                    skeCom.skeletonData = data[0];

                    pre.setParent(this.otherBiontRoot);
                    pre.scale = v3(this.getScaleNum(type), this.getScaleNum(type), 1);
                    pre.setPosition(randomNum(-this.mapBoundary.x, this.mapBoundary.x), randomNum(-this.mapBoundary.y, this.mapBoundary.y));
                    let biontCom = pre.addComponent(Biont);
                    biontCom.init(type);

                    skeCom.setAnimation(0, "animation", true);

                    let rig = pre.getChildByName("sp").addComponent(RigidBody2D);
                    let cod = pre.getChildByName("sp").addComponent(BoxCollider2D);
                    rig.type = ERigidBody2DType.Kinematic;
                    rig.enabledContactListener = true;
                    cod.sensor = true;
                    cod.size.width = skeCom.node.getComponent(UITransform).contentSize.x;
                    cod.size.height = skeCom.node.getComponent(UITransform).contentSize.y;


                }

            }
        })
    }

    createOtherBiontNotNearlySelf(type, num) {
        resources.loadDir(`shi/spine/shanhai_${type}`, sp.SkeletonData, (err, data) => {
            if (err) {
                console.log(err);
                return;
            } else {
                let pos = null;
                while (pos == null) {
                    pos = v2(randomNum(-this.mapBoundary.x + 500, this.mapBoundary.x - 500), randomNum(-this.mapBoundary.y + 500, this.mapBoundary.y - 500));
                    if (getDistance(this.player.position.x, this.player.position.y, pos.x, pos.y) < 700) {
                        pos = null;
                    }

                }

                for (let i = 0; i < num; i++) {
                    let pre = instantiate(this.biontPre);
                    let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                    skeCom.skeletonData = data[0];

                    pre.setParent(this.otherBiontRoot);
                    pre.scale = v3(this.getScaleNum(type), this.getScaleNum(type), 1);
                    pre.setPosition(pos.x,pos.y);
                    let biontCom = pre.addComponent(Biont);
                    biontCom.init(type);

                    skeCom.setAnimation(0, "animation", true);

                    let rig = pre.getChildByName("sp").addComponent(RigidBody2D);
                    let cod = pre.getChildByName("sp").addComponent(BoxCollider2D);
                    rig.type = ERigidBody2DType.Kinematic;
                    rig.enabledContactListener = true;
                    cod.sensor = true;
                    cod.size.width = skeCom.node.getComponent(UITransform).contentSize.x;
                    cod.size.height = skeCom.node.getComponent(UITransform).contentSize.y;


                }

            }
        })
    }

    //捕捉到生物
    captureBiont(biontType) {
        // AudioMgr.ins.playOneShot("audio/countDown", 0.7)
        console.log("捕捉")
        this.generateBiont(biontType);

        console.log(this.hasBiontsDic, "捕捉到的生物子字典")

        let isNeedReGenerateBiont = false;
        while (this.judgeIsHasThereBiont().length > 0) {
            console.log("合成自己0.1")
            let resArr = this.judgeIsHasThereBiont();
            if (resArr && resArr.length > 0) {//可以合成
                isNeedReGenerateBiont = true;
                if (this.currControlBiontType <= resArr[0]) {
                    console.log("合成自己")
                    this.selftChangeBiont(resArr[0] + 1)

                    this.hasBiontsDic.deleteValue(resArr[0]);
                    this.hasBiontsDic.deleteValue(resArr[1]);
                    // if (resArr.length>=3) {
                    this.hasBiontsDic.deleteValue(resArr[2]);
                    // }
                    this.hasBiontsDic.delete(999)
                    this.hasBiontsDic.set(999, resArr[0] + 1);

                }
                else {
                    console.log("合成附属")

                    this.hasBiontsDic.deleteValue(resArr[0]);
                    this.hasBiontsDic.deleteValue(resArr[1]);
                    if (resArr.length == 3) {
                        this.hasBiontsDic.deleteValue(resArr[2]);
                    }

                    this.hasBiontsDic.set(this.biontId, resArr[0] + 1);
                    this.biontId += 1

                }


            }
            else {
                console.log("不能合成")
                break;

            }

        }

        if (isNeedReGenerateBiont) {
            setTimeout(() => {
                this.reGenerateBiont();

            }, 50);
        }



    }

    generateBiont(biontType) {
        this.hasBiontsDic.set(this.biontId, biontType)
        this.biontId += 1;

        resources.loadDir(`shi/spine/shanhai_${biontType}`, sp.SkeletonData, (err, data) => {
            if (err) {
                console.log(err);
                return;
            } else {
                let pre = instantiate(this.biontPre);
                pre.scale = v3(this.getScaleNum(biontType), this.getScaleNum(biontType), 1);

                let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                skeCom.skeletonData = data[0];

                pre.setParent(this.addtionBiontRoot);

                pre.angle = 0;

                let randCount = randomNum(0, 1);
                let resY;
                if (randCount == 0) {
                    resY = randomNum(-60, -100)
                }
                else {
                    resY = randomNum(60, 100)
                }

                pre.setPosition(v3(randomNum(-80, -180), resY, 0))


                skeCom.setAnimation(0, "animation", true);

            }
        })


    }

    reGenerateBiont() {
        console.log(this.hasBiontsDic.getValueList(), "this.hasBiontsDic.getValueList()")
        this.addtionBiontRoot.removeAllChildren();

        this.hasBiontsDic.getKeyList().forEach((ele) => {
            if (ele == 999) {
                return;
            }

            resources.loadDir(`shi/spine/shanhai_${this.hasBiontsDic.get(ele)}`, sp.SkeletonData, (err, data) => {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let pre = instantiate(this.biontPre);
                    pre.scale = v3(this.getScaleNum(this.hasBiontsDic.get(ele)), this.getScaleNum(this.hasBiontsDic.get(ele)), 1);

                    let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                    skeCom.skeletonData = data[0];

                    pre.setParent(this.addtionBiontRoot);

                    pre.angle = 0;

                    let randCount = randomNum(0, 1);
                    let resY;
                    if (randCount == 0) {
                        resY = randomNum(-60, -100)
                    }
                    else {
                        resY = randomNum(60, 100)
                    }

                    pre.setPosition(v3(randomNum(-80, -180), resY, 0))


                    skeCom.setAnimation(0, "animation", true);

                }
            })
        })

    }

    //判断是否有三个一样的生物
    judgeIsHasThereBiont() {
        let typeArr = [this.currControlBiontType]
        let tempCount = 0;
        let resType = -1;
        let resArr = []
        this.hasBiontsDic.getValueList().forEach((ele) => {
            if (typeArr.indexOf(ele) == -1) {
                typeArr.push(ele)
            }
        })
        for (let t = 0; t < typeArr.length; t++) {
            tempCount = 0;
            for (let i = 0; i < this.hasBiontsDic.getValueList().length; i++) {
                console.log("执行到循环了")
                if (this.hasBiontsDic.getValueList()[i] == typeArr[t]) {
                    tempCount += 1

                    // if (tempCount == 2 && typeArr[t] == this.currControlBiontType) {
                    //     console.log("44")
                    //     resType = typeArr[t]
                    // }
                    if (tempCount == 3) {

                        resType = typeArr[t]
                    }
                }

            }

        }

        if (resType != -1) {
            this.hasBiontsDic.getValueList().forEach((ele) => {
                if (ele == resType) {
                    resArr.push(ele)
                }
            })
        }
        return resArr;
    }

    selftChangeBiont(biontType) {

        if (biontType >= 68) {//通关
            GameMgrShi.ins.gameEnd();
            return;
        }
        this.currControlBiontType = biontType;
        this.player.removeAllChildren()
        this.hasBiontsDic.delete(999)
        this.hasBiontsDic.set(999, biontType);

        resources.loadDir(`shi/spine/shanhai_${biontType}`, sp.SkeletonData, (err, data) => {
            if (err) {
                console.log(err);
                return;
            } else {
                let pre = instantiate(this.biontPre);
                pre.scale = v3(this.getScaleNum(biontType), this.getScaleNum(biontType), 1);
                let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                skeCom.skeletonData = data[0];

                pre.setParent(this.player);

                pre.angle = 0;

                skeCom.setAnimation(0, "animation", true);

                let rig = pre.getChildByName("sp").addComponent(RigidBody2D);
                let cod = pre.getChildByName("sp").addComponent(BoxCollider2D);
                rig.type = ERigidBody2DType.Kinematic;
                rig.enabledContactListener = true;
                rig.allowSleep = false;
                cod.size.width = skeCom.node.getComponent(UITransform).contentSize.x;
                cod.size.height = skeCom.node.getComponent(UITransform).contentSize.y;
                pre.getChildByName("sp").getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.beginTouch);

                if (this.isImmortal) {
                    //隐身效果
                    tween(this.player.children[0].getChildByName("sp").getComponent(UIOpacity))
                        .to(0.4, { opacity: 100 })
                        .to(0.4, { opacity: 255 })
                        .to(0.4, { opacity: 100 })
                        .union()
                        .repeatForever()
                        .start()
                }
                this.player.children[0].getChildByName("levelUpEffect").getComponent(sp.Skeleton).setAnimation(0, "animation", false);


            }
        })
        // AudioMgr.ins.playOneShot("audio/devour", 0.7)

    }

    getScaleNum(biontType) {
        let scaleNum = 1;
        if (biontType <= 48) {
            scaleNum = 0.35;
        }
        else if (biontType > 48 && biontType <= 54) {
            scaleNum = 0.5;
        }
        else if (biontType > 45 && biontType <= 61) {
            scaleNum = 0.65;
        }
        else {
            scaleNum = 0.8;
        }

        return scaleNum
    }

    gameEnd() {
        if (this.isGameIng == true) {
            console.log("合成最高级游戏结束");
            AudioMgr.ins.playOneShot("audio/lightning",0.7);

            this.isGameIng = false;
            this.winPanel.active = true;
            let skeComp = this.winPanel.getChildByName("sp").getComponent(sp.Skeleton);

            skeComp.setAnimation(0, "appearance", false);

            skeComp.setCompleteListener((trackEntry) => {
                let name = trackEntry.animation ? trackEntry.animation.name : '';
                if (name === "appearance") {
                    skeComp.setAnimation(0, "idle", true);
                    this.winPanel.getChildByName("bg").on(Node.EventType.TOUCH_START, () => {
                        this.winPanel.active = false;
                        this.openFailPanel();
                    })
                }
            });
        }
    }

    openFailPanel() {
        this.failPanel.active = true;
        let num = 1;
        num = (this.currControlBiontType - 42) * 3;
        if (this.currControlBiontType==43) {
            num = 1
        }
        if (this.currControlBiontType >= 67) {
            num = 99
        }
        this.failPanel.getChildByName("beatPlayerLabel").getComponent(Label).string = `击败了全球${num}%的玩家`;

    }


    gameOver() {
        if (this.isGameIng == true) {
            console.log("游戏结束");
            AudioMgr.ins.playOneShot("audio/lose",0.7);

            this.isGameIng = false;
            this.revivePanel.active = true;

            this.revivePanel.getChildByName("liangbeij").getChildByName("fishRoot").removeAllChildren();
            resources.loadDir(`shi/spine/shanhai_${this.currControlBiontType}`, sp.SkeletonData, (err, data) => {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let pre = instantiate(this.biontPre);
                    pre.scale = v3(this.getScaleNum(this.currControlBiontType), this.getScaleNum(this.currControlBiontType), 1);
                    let skeCom = pre.getChildByName("sp").getComponent(sp.Skeleton);
                    skeCom.skeletonData = data[0];

                    pre.setParent(this.revivePanel.getChildByName("liangbeij").getChildByName("fishRoot"));
                    pre.layer = 0;
                    pre.layer = Layers.Enum.UI_3D;
                    for (let i = 0; i < pre.children.length; i++) {
                        pre.children[i].layer = 0;
                        pre.children[i].layer = Layers.Enum.UI_3D;
                    }

                    skeCom.setAnimation(0, "animation", true);


                }
            })

        }

    }

    onclickReviveBtn() {
        AudioMgr.ins.playOneShot("audio/btn",0.7);

        this.revivePanel.active = false;
        this.isGameIng = true;
        this.IsImmortal=true;
          //5秒后自动解除
          this.scheduleOnce(()=>{
            this.IsImmortal=false;
        },5)

    }

    onclickCancelReviveBtn() {
        AudioMgr.ins.playOneShot("audio/btn",0.7);

        this.revivePanel.active = false;
        this.openFailPanel();

    }

    onclickJinhuaBtn() {
        this.selftChangeBiont(this.currControlBiontType + 1);
    }

    onclickShenkunBtn() {
        if (this.IsImmortal == true) {
            this.createWidowTip("正在无敌模式");
            return;
        }
        else {
            this.shenkunBtn.getComponent(Button).enabled = false;
            this.shenkunBtn.getComponent(sp.Skeleton).color = new Color().fromHEX("#929292");

            this.IsImmortal = true;
            this.shenkunTimeLabel.node.active = true;
            this.shenkunTimeLabel.string = 20 + "";
            TouchMoveShi.ins.moveSpeed += 8;

            let timeCount = 20;
            this.schedule(() => {
                timeCount -= 1;
                this.shenkunTimeLabel.string = timeCount + "";
                if (timeCount == 0) {
                    this.shenkunBtn.getComponent(Button).enabled = true;
                    this.shenkunBtn.getComponent(sp.Skeleton).color = Color.WHITE;

                    this.shenkunTimeLabel.node.active = false;
                    this.IsImmortal = false;
                    TouchMoveShi.ins.moveSpeed -= 8;

                }
            }, 1, 19)
        }

    }

    onclickSetBtn() {
        AudioMgr.ins.playOneShot("audio/btn",0.7);

        this.isGameIng = false;
        this.setPanel.active = true;
        this.renewAudioUI();
    }

    onclickContinueGameBtn() {
        this.isGameIng = true;
        this.setPanel.active = false;
    }

    returnHome() {
        AudioMgr.ins.playOneShot("audio/btn",0.7);

        director.loadScene("home")
    }

    createWidowTip(str) {
        let pre = instantiate(this.widowTipPre);
        pre.setParent(find("Canvas"));
        pre.setPosition(0, -50);
        pre.getChildByName("Label").getComponent(Label).string = str;
        tween(pre)
            .to(0.5, { position: v3(0, 0, 0) })
            .delay(2)
            .call(() => {
                pre.destroy();
            })
            .start()
    }

      onclickSetPanelaudioEffectBtn(){
            if (UserInfo.isAudioEffect) {
            UserInfo.isAudioEffect=false;
            }
            else{
            UserInfo.isAudioEffect=true;
            }
    
            this.renewAudioUI();
        }
        onclickSetPanelBgmBtn(){
            if (UserInfo.isAudioBgm) {
                UserInfo.isAudioBgm=false;
                AudioMgr.ins.stop();
            }
            else{
                UserInfo.isAudioBgm=true;
                AudioMgr.ins.play("audio/bgm");
            }
            this.renewAudioUI();
    
        }
    
    
        renewAudioUI() {
            if (UserInfo.isAudioBgm) {
                resources.load("audioImg/starOn/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("bgmBtn").getChildByName("star").getComponent(Sprite).spriteFrame = res;
    
                })
                resources.load("audioImg/itemBgOn/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("bgmBtn").getChildByName("bg").getComponent(Sprite).spriteFrame = res;
    
                })
                this.setPanel.getChildByName("bgmBtn").getChildByName("star").setPosition(50,0);
            }
            else {
                resources.load("audioImg/starOff/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("bgmBtn").getChildByName("star").getComponent(Sprite).spriteFrame = res;
    
                })
                resources.load("audioImg/itemBgOff/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("bgmBtn").getChildByName("bg").getComponent(Sprite).spriteFrame = res;
    
                })
                this.setPanel.getChildByName("bgmBtn").getChildByName("star").setPosition(-50,0);
             
            }
    
            if (UserInfo.isAudioEffect) {
                resources.load("audioImg/starOn/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("effectBtn").getChildByName("star").getComponent(Sprite).spriteFrame = res;
    
                })
                resources.load("audioImg/itemBgOn/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("effectBtn").getChildByName("bg").getComponent(Sprite).spriteFrame = res;
    
                })
                this.setPanel.getChildByName("effectBtn").getChildByName("star").setPosition(50,0);
    
            }
            else {
                resources.load("audioImg/starOff/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("effectBtn").getChildByName("star").getComponent(Sprite).spriteFrame = res;
    
                })
                resources.load("audioImg/itemBgOff/spriteFrame", SpriteFrame, (err, res) => {
                    this.setPanel.getChildByName("effectBtn").getChildByName("bg").getComponent(Sprite).spriteFrame = res;
    
                })
                this.setPanel.getChildByName("effectBtn").getChildByName("star").setPosition(-50,0);
    
            }
        }
    


    // assetManager.loadBundle('resources2', (err, bundle) => {
    //     if (err) {
    //         console.error('加载资源包失败:', err);
    //         return;
    //     }

    //     // 加载资源包中的资源

    //     bundle.loadDir('spine/level_25',sp.SkeletonData,(err,data)=>{
    //         if(err){
    //             console.log(err);
    //             return;
    //         }else{
    //             let comp = this.player.children[0].getChildByName("sp").getComponent(sp.Skeleton);
    //             comp.skeletonData = data[0];
    //         }
    //     })

    // });


}


